/**
 * 计算对象大小的函数-用于计算对象占用的内存大小
 * @param obj 需要计算的对象
 * @returns 对象占用的内存大小 byte
 */
export const getObjectSize = (obj: unknown): number => {
  let bytes = 0
  function sizeOf(obj: unknown) {
    if (obj !== null && typeof obj !== 'undefined') {
      switch (typeof obj) {
        case 'number':
          bytes += 8
          break
        case 'string':
          bytes += obj.length * 2
          break
        case 'boolean':
          bytes += 4
          break
        case 'object': {
          const objClass = Object.prototype.toString.call(obj).slice(8, -1)
          if (objClass === 'Object' || objClass === 'Array') {
            if (objClass === 'Array') {
              bytes += (obj as unknown[]).length * 8
            }

            for (const key in obj) {
              if (!Object.prototype.hasOwnProperty.call(obj, key)) {
                continue
              }
              bytes += key.length * 2
              sizeOf((obj as Record<string, unknown>)[key])
            }
          } else {
            bytes += obj.toString().length * 2
          }
          break
        }
      }
    }
    return bytes
  }

  return sizeOf(obj)
}
